[<<Previous Entry]
[^^Up^^]
[Next Entry>>]
[Menu]
[About The Guide]
split(/PATTERN/,EXPR,LIMIT)
split(/PATTERN/,EXPR)
split(/PATTERN/)
split Splits a string into an array of strings, and
returns it. (If not in an array context, returns
the number of fields found and splits into the @_
array. (In an array context, you can force the
split into @_ by using ?? as the pattern delimiters,
but it still returns the array value.)) If EXPR is
omitted, splits the $_ string. If PATTERN is also
omitted, splits on whitespace (/[ \t\n]+/). Any-
thing matching PATTERN is taken to be a delimiter
separating the fields. (Note that the delimiter may
be longer than one character.) If LIMIT is speci-
fied, splits into no more than that many fields
(though it may split into fewer). If LIMIT is
unspecified, trailing null fields are stripped
(which potential users of pop() would do well to
remember). A pattern matching the null string (not
to be confused with a null pattern //, which is just
one member of the set of patterns matching a null
string) will split the value of EXPR into separate
characters at each point it matches that way. For
example:
print join(':', split(/ */, 'hi there'));
produces the output 'h:i:t:h:e:r:e'.
The LIMIT parameter can be used to partially split a
line
($login, $passwd, $remainder) = split(/:/, $_, 3);
(When assigning to a list, if LIMIT is omitted, perl
supplies a LIMIT one larger than the number of vari-
ables in the list, to avoid unnecessary work. For
the list above LIMIT would have been 4 by default.
In time critical applications it behooves you not to
split into more fields than you really need.)
If the PATTERN contains parentheses, additional
array elements are created from each matching sub-
string in the delimiter.
split(/([,-])/,"1-10,20");
produces the array value
(1,'-',10,',',20)
The pattern /PATTERN/ may be replaced with an
expression to specify patterns that vary at runtime.
(To do runtime compilation only once, use
/$variable/o.) As a special case, specifying a
space (' ') will split on white space just as split
with no arguments does, but leading white space does
NOT produce a null first field. Thus, split(' ')
can be used to emulate awk's default behavior,
whereas split(/ /) will give you as many null ini-
tial fields as there are leading spaces.
Example:
open(passwd, '/etc/passwd');
while (<passwd>) {
($login, $passwd, $uid, $gid, $gcos, $home, $shell)
= split(/:/);
...
}
(Note that $shell above will still have a newline on
it. See chop().) See also join.
This page created by ng2html v1.05, the Norton guide to HTML conversion utility.
Written by Dave Pearson